什么是mutex
互斥锁(Mutual exclusion,缩写Mutex)是一种用于多线程编程中,防止两条线程对同一公共资源(比如全局变量)进行读写的机制。通过将代码分割成一个一个的临界区域(critical section)达成这样的效果。
C++ mutex
在C++11中针对并发编程提供了如下的mutex(各有特性):
std::mutex
std::recursive_mutex
std::timed_mutex
std::recursive_timed_mutex
且还提供了如下用于辅助的模版类:
template class lock_guard;
template class unique_lock;
基本mutex样例
std::mutex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| void printer(char c) { mtx.lock(); for(int i = 0;i < 20;i++) cout<< c; cout<<endl; mtx.unlock(); } int main() { thread t(printer, '*'); thread t1(printer, '!'); t.join(); t1.join(); }
|
std::recurisve_mutex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| void printer(char c) { rmtx.lock(); rmtx.lock(); rmtx.unlock(); rmtx.unlock(); for(int i = 0;i < 20;i++) cout<< char(c+1); cout<<endl; mtx.lock(); mtx.lock(); for(int i = 0;i < 20;i++) cout<< c; cout<<endl; mtx.unlock(); } int main() { thread t(printer, '*'); t.join(); }
|
std::timed_mutex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| void printer(char c) { tmtx.try_lock_for(chrono::nanoseconds(1)); for(int i = 0;i < 20;i++) cout<< c; cout<<endl; } int main() { thread t(printer, '*'); thread t2(printer, '+'); t.join(); t2.join(); }
|
省略recursive_timed_mutex